const path = require("path");
const hotMiddlewareScript = "webpack-hot-middleware/client?reload=true";
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const CommonsChunkPlugin = require("webpack/lib/optimize/CommonsChunkPlugin");
const OpenBrowserPlugin = require("open-browser-webpack-plugin");
const CleanWebpackPlugin = require('clean-webpack-plugin');
const UglifyJSPlugin = require("uglifyjs-webpack-plugin");
const CopyWebpackPlugin = require('copy-webpack-plugin');
const glob = require("glob");
const entries = {};
const chunks = [];
const prodEntries = {};
const prodChunks = [];


//服务器启动IP与端口
const svrConfig = {
    host: "0.0.0.0",//为的是让其他人，能根据前台服务器的ip, 访问前台服务器
    // host: "10.6.208.234",
    port: 3000,
    //是否开启静默模式？true开启，紧显示错误和警告，如要看信息为false。
    noInfo: false
};

//代理模式切换，enable:true启用代理，数据模拟失效.只对开发有效
const proxyConfig = [{
    enable: true,
    router: "/",
    url: "10.11.88.20:8080",
    options: {
        filter: function (req, res) {
            return (req.url.indexOf("webpack_hmr") > -1 ? false : true);
        }
    }
}];

//静态资源托管设置
const staticConfig = {
    folder: "src/docs"
};

//优化配置，对于使用CDN作为包资源的引用从外到内的配置
const externals = {
    "react": "React",
    "react-dom": "ReactDOM",
    "react-router": "ReactRouter",
    "axios": "axios",
    "redux": "Redux"
}

//默认加载扩展名、相对JS路径模块的配置
const resolve = {
    extensions: [
        ".js", ".jsx"
    ],
    alias: {
        components: path.resolve(__dirname, "src/components/"),
        assets: path.resolve(__dirname, "src/assets/"),
        pages: path.resolve(__dirname, "src/pages/"),
        utils: path.resolve(__dirname, "src/utils/"),
        layout: path.resolve(__dirname, "src/layout/")
    }
}

//开发和生产需要的loader
const rules = [{
    test: /\.js[x]?$/,
    exclude: /(node_modules)/,
    include: path.resolve("src"),
    use: [{
        loader: "babel-loader"
    }]
}, {
    test: /\.css$/,
    use: ExtractTextPlugin.extract({
        use: ["css-loader", "postcss-loader"],
        fallback: "style-loader"
    })
}, {
    test: /\.less$/,
    use: ExtractTextPlugin.extract({
        use: ['css-loader', 'postcss-loader', 'less-loader'],
        fallback: 'style-loader'
    })
}, {
    test: /\.(png|jpg|jpeg|gif)(\?.+)?$/,
    exclude: /favicon\.png$/,
    use: [{
        loader: "url-loader",
        options: {
            limit: 10000,
            name: "images/[name].[ext]"
        }
    }]
}, {
    test: /\.(eot|ttf|woff|woff2|svg|svgz)(\?.+)?$/,
    use: [{
        loader: "file-loader",
        options: {
            name: "[name].[ext]"
        }
    }]
}];

//dev多入口配置
glob.sync("./src/home/*/index.js").forEach(path => {
    const chunk = path.split("./src/home/")[1].split("/index.js")[0];
    entries[chunk] = ["babel-polyfill", path, hotMiddlewareScript];
    chunks.push(chunk);
});


//dev webpack基本配置
var devConfig = {
    devtool: "cheap-module-source-map",
    entry: entries,
    output: {
        path: path.resolve(__dirname, "../pmclouds-customer/src/main/resources/static"),
        filename: "[name].js",
        publicPath: "/"
    },
    externals: externals,
    module: {
        rules: rules
    },
    plugins: [
        new CopyWebpackPlugin([
            {
                from: "src/utils",
                to: "",
                ignore: ['ajaxConfig.js', 'config.js', 'animate.js', 'cdata.js', 'city.js', 'network.config.js', 'networkutils.js', 'slider.js','fastclick.js'],
                flatten: true
            }
        ]),
        new CommonsChunkPlugin({
            name: "vendors",
            filename: "vendors.js",
            chunks: chunks,
            minChunks: chunks.length
        }),
        new ExtractTextPlugin({
            filename: "[name].css",
            allChunks: true
        }),
        new OpenBrowserPlugin({
            url: `http://${svrConfig.host}:${svrConfig.port}`
        }),
        new webpack.HotModuleReplacementPlugin(),
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: JSON.stringify('dev')
            }
        })
    ],
    resolve: resolve
}


//多页面配置
glob.sync("./src/home/*/index.html").forEach(path => {
    const chunk = path.split("./src/home/")[1].split("/index.html")[0];
    const filename = chunk + ".html";
    const htmlConf = {
        filename: filename,
        template: path,
        inject: "body",
        // favicon: "./src/assets/image/favicon.png",
        hash: true,
        chunks: ["vendors", chunk],
        xhtml: true
    };
    devConfig.plugins.push(new HtmlWebpackPlugin(htmlConf));
});



//product多入口配置
glob.sync("./src/home/*/index.js").forEach(path => {
    const chunk = path.split("./src/home/")[1].split("/index.js")[0];
    prodEntries[chunk] = ["babel-polyfill", path];
    prodChunks.push(chunk);
});

//product webpack基本配置
var prodConfig = {
    entry: prodEntries,
    output: {
        path: path.resolve(__dirname, "../pmclouds-customer/src/main/resources/static"),
        filename: "[name].[hash:8].js",
        publicPath: ""
    },
    externals: externals,
    module: {
        rules: rules
    },
    plugins: [
        new CopyWebpackPlugin([
            {
                from: "src/utils",
                to: "",
                ignore: ['ajaxConfig.js', 'config.js', 'animate.js', 'cdata.js', 'city.js', 'network.config.js', 'networkutils.js', 'slider.js','fastclick.js'],
                flatten: true
            }
        ]),
        /*new CommonsChunkPlugin({
            name: "vendors",
            filename: "vendors.[hash:8].js",
            chunks: prodChunks,
            minChunks: prodChunks.length
        }),*/
        new ExtractTextPlugin({
            filename: "[name].[hash:8].css",
            allChunks: true
        }),
        new CleanWebpackPlugin(['*.*'],
            {
                root: path.resolve(__dirname, "../pmclouds-customer/src/main/resources/static"),       　　　　　　　　　　//根目录
                verbose: true,        　　　　　　　　　　//开启在控制台输出信息
                dry: false        　　　　　　　　　　//启用删除文件
            }),
        new UglifyJSPlugin(),
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: JSON.stringify('production')
            }
        })
    ],
    resolve: resolve
}

//多页面配置
glob.sync("./src/home/*/index.html").forEach(path => {
    const chunk = path.split("./src/home/")[1].split("/index.html")[0];
    const filename = chunk + ".html";
    const htmlConf = {
        filename: filename,
        template: path,
        inject: "body",
        // favicon: "./src/assets/images/favicon.png",
        hash: true,
        chunks: ["vendors", chunk],
        xhtml: true
    }
    prodConfig.plugins.push(new CommonsChunkPlugin({
        name: "vendors",
        filename: "vendors.[hash:8].js",
        chunks: chunk,
        minChunks: chunk.length
    }));
    prodConfig.plugins.push(new HtmlWebpackPlugin(htmlConf));
});

module.exports = {
    devConfig,
    prodConfig,
    svrConfig,
    proxyConfig,
    staticConfig
};
